package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.adapter.BaiduMapPointSuggestionAdapter;
import com.wuliupai.delivery.wuliupaidelivery.bean.OrderBean;
import com.wuliupai.delivery.wuliupaidelivery.constants.InterfaceNet;
import com.wuliupai.delivery.wuliupaidelivery.constants.Value;
import com.wuliupai.delivery.wuliupaidelivery.db.CityHistoryBean;
import com.wuliupai.delivery.wuliupaidelivery.net.NetResultOperate;
import com.wuliupai.delivery.wuliupaidelivery.ui.CustomListView;
import com.wuliupai.delivery.wuliupaidelivery.utils.CityUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.LogUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.StringUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.TextChange;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;


/**
 * Descriptions：填写收发货信息页面
 * <p>
 * Author：ChenME
 * Date：2017/1/6
 * Email：ibelieve1210@163.com
 */
@EActivity(R.layout.activity_send_or_pick_up_info)
public class EditSendOrPickUpInfoActivity extends AppBaseActivity {

    @ViewById(R.id.tv_addressLabel)
    TextView tv_addressLabel;//地址
    @ViewById(R.id.tv_address)
    TextView tv_address;//地址
    @ViewById(R.id.et_addressDetail)
    EditText et_addressDetail;//详细地址
    @ViewById(R.id.et_addressDetail2)
    EditText et_addressDetail2;//详细地址

    @ViewById(R.id.lv_suggestionResult)
    CustomListView lv_suggestionResult;

    @ViewById(R.id.tv_personLabel)
    TextView tv_personLabel;//联系人
    @ViewById(R.id.et_person)
    EditText et_person;//联系人
    @ViewById(R.id.et_phone)
    EditText et_phone;//电话

    @ViewById(R.id.iv_dividerAboveTips)
    ImageView iv_dividerAboveTips;//联系电话下提示TextView上面的分割线
    @ViewById(R.id.tv_tips)
    TextView tv_tips;//联系电话下提示TextView

    @Extra("whichPage")
    int whichPage;

    @Extra("resultPerson")
    String resultPerson = "";
    @Extra("resultPhone")
    String resultPhone = "";
    @Extra("resultAddress")
    String resultAddress = "";
    @Extra("resultCityBean")
    CityHistoryBean resultCityBean;

    @Extra("orderBean")
    OrderBean orderBean;

    private String resultGpsX = "";
    private String resultGpsY = "";

    public static final int Result_CompleteInfo = 0x4429;
    private static final int Request_GetPlace = 0x4428;
    private static final int Request_SendOrPickUpInfo = 0x1121;//常用收发货信息

    public static final int Page_ToInfo = 0x4427;//收
    public static final int Page_FromInfo = 0x4426;//发
    public static final int Page_CommFromInfoList = 0x4425;//常用发货信息列表
    public static final int Page_CommToInfoList = 0x4424;//常用收货信息列表

    private String addressResult;

    private SuggestionSearch mSuggestionSearch;
    private BaiduMapPointSuggestionAdapter mAdapter;
    private List<SuggestionResult.SuggestionInfo> suggestionInfoList;

    private SuggestionResult.SuggestionInfo resultSuggestionInfo;//结果
    private boolean isGetSuggestInfo = true;//是否开始获取百度在线查询
    private boolean isEditTextEmpty = true;//EditText是否为空


    @AfterViews
    void onPageStart() {

        initSuggestion();

        int titleRes = R.string.string_senOrPickUp_fromTitle;
        switch (whichPage) {
            case Page_ToInfo:
                titleRes = R.string.string_senOrPickUp_toTitle;
                setToHint();
                break;
            case Page_CommFromInfoList:
                if (null == orderBean) {//添加 发货
                    titleRes = R.string.string_senOrPickUp_fromAddTitle;
                } else {//编辑 发货
                    initDataByOrderBean(orderBean);
                    titleRes = R.string.string_senOrPickUp_fromEditTitle;
                }
                break;
            case Page_CommToInfoList:
                if (null == orderBean) {//添加 收货
                    titleRes = R.string.string_senOrPickUp_toAddTitle;
                } else {//编辑 收货
                    initDataByOrderBean(orderBean);
                    titleRes = R.string.string_senOrPickUp_toEditTitle;
                }
                setToHint();
                break;
        }
        setTitle(this, titleRes, R.drawable.comm_press_return_selector,
                true, new OnNavigationBtnClickListener() {
                    @Override
                    public void navigationClick() {
                        finish();
                        animUtils.leftOutAnimation(EditSendOrPickUpInfoActivity.this);
                    }

                    @Override
                    public void menuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.menuItem1:
                                FastOrder_CommSendOrPickUpInfo_Activity_.
                                        intent(EditSendOrPickUpInfoActivity.this)
                                        .whichPage(whichPage == Page_ToInfo ?
                                                FastOrder_CommSendOrPickUpInfo_Activity.Page_CommToInfo :
                                                FastOrder_CommSendOrPickUpInfo_Activity.Page_CommFromInfo)
                                        .startForResult(Request_SendOrPickUpInfo);
                                animUtils.leftInAnimation(EditSendOrPickUpInfoActivity.this);
                                break;
                        }
                    }
                });

        if (null != resultCityBean) {
            bindAllData();
        }
    }

    /**
     * 创建初始化在线建议查询功能
     */
    private void initSuggestion() {
        mSuggestionSearch = SuggestionSearch.newInstance();
        suggestionInfoList = new ArrayList<>();
        mAdapter = new BaiduMapPointSuggestionAdapter(this, suggestionInfoList);
        lv_suggestionResult.setAdapter(mAdapter);

        mSuggestionSearch.setOnGetSuggestionResultListener(res -> {
            if (res == null || res.getAllSuggestions() == null) {
                LogUtils.log("未找到相关结果");
                return;
            }

            List<SuggestionResult.SuggestionInfo> tempList = res.getAllSuggestions();
            for (int i = 0; i < tempList.size(); i++) {
//                info.key + " - " + info.city + "," + info.district;
                SuggestionResult.SuggestionInfo info = tempList.get(i);
                LogUtils.log("~~~~建议结果~~~\n" + info.city + " - " + info.district);
            }

            if (null != tempList && tempList.size() > 0 && !isEditTextEmpty) {

                //删除泛指名称，该泛指数据不会带有经纬度等信息
                for (int i = 0; i < tempList.size(); i++) {
                    if (null == tempList.get(i).pt) {
                        tempList.remove(i);
                    }
                }

                showOrHideBottomView(false);
                suggestionInfoList.addAll(tempList);
                mAdapter.notifyDataSetChanged();
            }
        });

        lv_suggestionResult.setOnItemClickListener((parent, view, position, id) -> {
            resultSuggestionInfo = suggestionInfoList.get(position);
            isGetSuggestInfo = false;
            et_addressDetail.setText(mAdapter.getSuggestionInfo(resultSuggestionInfo));
            showOrHideBottomView(true);
        });
    }

    /**
     * 当“输入搜索所在区域”内容被改变时
     */
    @TextChange(R.id.et_addressDetail)
    void onKeyInputChanged() {
        if (!isGetSuggestInfo) {
            isGetSuggestInfo = true;
            return;
        }
        if (et_addressDetail.isFocused()) {
            String key = et_addressDetail.getText().toString().trim();
            String city = null == resultCityBean ? "全国" : resultCityBean.getCity();
            if (key.length() > 0) {
                isEditTextEmpty = false;
                mSuggestionSearch.requestSuggestion(new SuggestionSearchOption().keyword(key).city(city));
            } else {
                isEditTextEmpty = true;
            }
            suggestionInfoList.clear();
            showOrHideBottomView(true);
        }
    }

    /**
     * 当手机号发生变化时触发
     */
    @TextChange(R.id.et_phone)
    void onPhoneInputChanged() {
        if (Page_FromInfo == whichPage) {
            String phoneNum = et_phone.getText().toString().trim();
            if (phoneNum.length() >= 11) {

                searchInfoFromServer(phoneNum);
            } else {
                showOrHidePhoneTipsView(false);
            }
        }
    }

    /**
     * 从网络上搜索发货信息
     *
     * @param phoneNum
     */
    private void searchInfoFromServer(String phoneNum) {
        //TODO 从网络上搜索发货信息
        showOrHidePhoneTipsView(false);
    }

    /**
     * 显示或隐藏手机号匹配结果
     *
     * @param isShow
     */
    private void showOrHidePhoneTipsView(boolean isShow) {
        iv_dividerAboveTips.setVisibility(isShow ? View.VISIBLE : View.GONE);
        tv_tips.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    /**
     * 显示或隐藏底部视图
     *
     * @param isShow 是否显示
     */
    private void showOrHideBottomView(boolean isShow) {
        lv_suggestionResult.setVisibility(isShow ? View.GONE : View.VISIBLE);
    }

    /**
     * 将所有的数据绑定到控件上
     */
    private void bindAllData() {
        setAddressResult();
        et_person.setText(resultPerson);
        et_phone.setText(resultPhone);
        et_addressDetail.setText(resultAddress);
    }

    /**
     * 通过OrderBean初始化页面的所有数据
     */
    private void initDataByOrderBean(OrderBean bean) {
        CityUtil cityUtil = new CityUtil(this);

        String pCode = bean.getProvinceCode();
        String cCode = bean.getCityCode();
        String aCode = bean.getAreaCode();

        String pName = cityUtil.findProvinceName(pCode);
        String cName = cityUtil.findCityName(cCode);
        String aName = cityUtil.findAreaName(aCode);
        resultCityBean = new CityHistoryBean(aCode, cCode, pCode, aName, cName, pName);

        resultPerson = bean.getName();
        resultPhone = bean.getMobile();
        resultAddress = bean.getAddress();

        resultGpsX = bean.getGps_x();
        resultGpsY = bean.getGps_y();

        bindAllData();
    }

    /**
     * 设置收货信息的提示文字
     */
    private void setToHint() {
        tv_addressLabel.setText(R.string.string_senOrPickUp_toAddressLabel);
        tv_personLabel.setText(R.string.string_senOrPickUp_toPersonLabel);
        et_person.setHint(R.string.string_senOrPickUp_toPersonHint);
    }

    /**
     * 设置title右侧按键样式
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.menuItem1).setVisible(true).setTitle("常用");
        menu.findItem(R.id.menuItem2).setVisible(false);
        return Page_ToInfo == whichPage || Page_FromInfo == whichPage;
    }

    /**
     * 地址选择结果返回
     *
     * @param resultCode
     * @param data
     */
    @OnActivityResult(Request_GetPlace)
    void onSelectPlaceResult(int resultCode, Intent data) {
        if (PlaceSelectActivityStep1.Result_CompleteAddress == resultCode) {

            String[] resultArea = data.getStringArrayExtra("area");
            String[] resultCity = data.getStringArrayExtra("city");
            String[] resultProvince = data.getStringArrayExtra("province");
            resultCityBean = new CityHistoryBean(resultArea[0], resultCity[0], resultProvince[0],
                    resultArea[1], resultCity[1], resultProvince[1]);
            setAddressResult();
        }
    }

    /**
     * 常用收发货信息返回结果
     *
     * @param resultCode
     * @param data
     */
    @OnActivityResult(Request_SendOrPickUpInfo)
    void onSendOrPickUpInfoResult(int resultCode, Intent data) {
        if (FastOrder_CommSendOrPickUpInfo_Activity.Result_CompleteOrderChose == resultCode) {
            OrderBean bean = data.getParcelableExtra("orderBean");
            if (null != bean) {
                initDataByOrderBean(bean);
            }
        }
    }

    private void setAddressResult() {
        addressResult = resultCityBean.getProvince() + " - " + resultCityBean.getCity() + " - " + resultCityBean.getArea();
        tv_address.setText(addressResult);
    }

    /**
     * 地址选择
     */
    @Click(R.id.tv_address)
    void onAddressClick() {
        PlaceSelectActivityStep1_.intent(this).startForResult(Request_GetPlace);
        animUtils.leftInAnimation(this);
    }

    /**
     * 确定
     */
    @Click(R.id.btn_confirmBtn)
    void onConfirmClick() {

        resultAddress = et_addressDetail.getText().toString().trim();
        resultPerson = et_person.getText().toString().trim();
        resultPhone = et_phone.getText().toString().trim();
        try {
            LatLng pt = resultSuggestionInfo.pt;
            resultGpsX = pt.longitude + "";
            resultGpsY = pt.latitude + "";
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (StringUtils.isEmpty(addressResult)) {
            App.toast("请选择所在城市");
            return;
        }
        if (StringUtils.isEmpty(resultAddress)) {
            App.toast(R.string.string_senOrPickUp_sendAddressAreaHint);
            return;
        }
        if (StringUtils.isEmpty(resultPerson)) {
            App.toast("请输入联系人");
            return;
        }
        if (StringUtils.isEmpty(resultPhone)) {
            App.toast("请输入联系电话");
            return;
        }

        if (null == resultSuggestionInfo) {
            resultAddress = et_addressDetail.getText().toString().trim()
                    + et_addressDetail2.getText().toString().trim();
        } else {
            resultAddress = resultSuggestionInfo.key
                    + et_addressDetail2.getText().toString().trim();
        }

        if (Page_FromInfo == whichPage || Page_ToInfo == whichPage) {
            Intent intent = new Intent();
            intent.putExtra("resultCityBean", resultCityBean);
            intent.putExtra("resultPerson", resultPerson);
            intent.putExtra("resultPhone", resultPhone);
            intent.putExtra("resultAddress", resultAddress);
            intent.putExtra("resultGpsX", resultGpsX);
            intent.putExtra("resultGpsY", resultGpsY);
            setResult(Result_CompleteInfo, intent);
            onBackPressed();
        } else {
            uploadInfo();
        }
    }

    /**
     * 上传常用收发货信息
     */
    private void uploadInfo() {

        String url = "";
        OrderBean requestBean = new OrderBean(resultCityBean.getProvinceCode(),
                resultCityBean.getCityCode(), resultCityBean.getAreaCode(),
                resultAddress, resultPerson, resultPhone);
        requestBean.setGps_x(resultGpsX);
        requestBean.setGps_y(resultGpsY);

        if (null == orderBean) {//新增
            url = InterfaceNet.Net_UploadCommSendOrPickUpInfo;
        } else {//编辑
            url = InterfaceNet.Net_EditCommSendOrPickUpInfo;
            requestBean.setId(orderBean.getId());
        }

        if (Page_CommFromInfoList == whichPage) {
            requestBean.setType("1");
        } else {
            requestBean.setType("2");
        }

        String requestJson = JsonUtils.createJsonString(requestBean);
        LogUtils.log("常用收发货信息提交~~" + requestJson);
        try {
            String requestAes = JsonUtils.aes(requestJson);
            callNet(this, url, requestAes, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
                    setResult(Value.ResultCode_Comm, null);
                    onBackPressed();
                }

                @Override
                public void onDataEmpty(String content) {
                }

                @Override
                public void onDataEnd(String content) {
                }

                @Override
                public void onErr(String errorCode, String errorMsg, Context mContext) {
                    super.onErr(errorCode, errorMsg, mContext);

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        animUtils.leftOutAnimation(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSuggestionSearch.destroy();
        mSuggestionSearch = null;
    }
}